var soon = {}

soon.ajax = function (settings) {

    settings = $.extend({
        async: true,
        beforeSend: function () { },
        cache: false,
        data: {},
        dataType: "json",
        error: function () { },
        success: function () { },
        type: "post",
        url: "",
        errroMsg: "请求失败，服务器繁忙",
        isError: true,
    }, settings || {});

    if (settings.loading != false) {
        settings.loadingid = layer.load(0);
    }

    settings.data._isajax = "true";

    $.ajax({
        async: settings.async,
        beforeSend: settings.beforeSend,
        cache: settings.cache,
        contentType: settings.contentType,
        data: settings.data,
        type: settings.type,
        url: settings.url,
        dataType: settings.dataType,
        error: function (err) {
            setTimeout(function () {
                layer.close(settings.loadingid);
            }, 100);
            if (settings.isError) {
                layer.msg(settings.errroMsg);
            }
            settings.error(err);
            console.log(err);
        },
        success: function (data, textStatus, jqXHR) {
            setTimeout(function () {
                layer.close(settings.loadingid);
            }, 100);
            settings.success(data, textStatus, jqXHR);
        }
    });

};
soon.open = function (settings) {

    settings = $.extend({
        url: "",
        data: {},
        id: $.Guid(),
        title: "",
        width: "80%",
        height: "80%",
        iframe: false,
        btn: undefined,
        closeBtn: 1,
        shade: 0.4,
        content: '',

        success: function () {

        }, error: function () {

        }, end: function () {

        }, brn2: function () {

        }, brn3: function () {

        }
    }, settings || {});

    if (settings.iframe == false) {

        var xhhd;

        var inx = layer.open({
            id: settings.id,
            title: settings.title,
            area: [settings.width, settings.height],
            type: 1,
            content: settings.content,
            btn: settings.btn,
            zIndex: 9999,
            closeBtn: settings.closeBtn,
            shade: settings.shade,
            scrollbar: false,
            yes: function () {
                settings.success();
            }, end: function () {

                try {
                    if (xhhd) {
                        //销毁后清除无效标签
                        xhhd.each(function () {
                            $(this).data().combo.panel.panel("destroy");
                        });
                    }
                } catch (e) {

                }

                settings.end();

            },
            btn2: settings.btn2,
            btn3: settings.btn3,
        });

        settings.data._openid = inx;

        if (settings.url != undefined && settings.url != "") {

            soon.ajax({
                url: settings.url,
                data: settings.data,
                dataType: "text",
                success: function (data) {
                    $("#" + settings.id).html(data);
                },
                error: function (data) {
                    var id = "err_" + $.Guid();
                    $("#" + settings.id).html('<iframe scrolling="no" frameborder="0"  id="' + id + '" style="width:99%;height:99%;"></iframe>');
                    $("#" + id).contents().find("html").html(data);
                }
            });

        }

        soon._openid = inx;

        return inx;

    } else {
        var inx = layer.open({
            id: settings.id,
            title: settings.title,
            area: [settings.width, settings.height],
            type: 2,
            content: settings.url,
            btn: settings.btn,
            closeBtn: settings.closeBtn,
            zIndex: 9999,
            scrollbar: false,
            yes: function () {
                settings.success();
            },
            end: function () {
                settings.end();
            }
        });
        $.soon._openid = inx;
    }


};
soon.captcha = function (fn) {

    var val = "";
    var load = function () {
        $.soon.ajax({
            url: "/Unit/Captcha",
            success: function (data) {
                $("#layui-layer" + index + " img").attr("src", data.img);
                val = data.val;
            }
        });
    };
    var index = layer.open({
        type: 1,
        title: "请输入图形验证码",
        content: "<div class='page-captcha'><input type='text' name='code' placeholder='验证码'  /><img alt='点此刷新验证码'/></div>",
        btn: ["确认", "取消"],
        yes: function () {
            var code = $("#layui-layer" + index + " input[name='code']").val();
            if (code == "") {
                layer.msg("请输入图形验证码");
            } else {
                layer.close(index);
                fn(code, val);
            }
        }
    });

    $("#layui-layer" + index + " img").click(function () {
        load();
    });
    load();
};
soon.search = function (settings) {
    settings = $.extend({
        url: "",
        tag: "",
        data: {},
        textField: "text",
        valueField: "id",
        width: 0,
        height: "100px",
        click: function (tag, data) {

        }
    }, settings || {});

    if (settings.tag != "" && settings.tag != "") {
        if (settings.width == 0) {
            settings.width = $(settings.tag).width() + "px";
        }

        var load = function () {
            settings.data.val = $(settings.tag).val();
            $(settings.tag).parent().find(".page-search").remove();
            if (settings.data.val.length > 1) {
                $.ajax({
                    url: settings.url,
                    data: settings.data,
                    dataType: "json",
                    type: "post",
                    success: function (data) {
                        if (data.length > 0) {
                            var html = "<div class='page-search'>";
                            for (var i = 0; i < data.length; i++) {
                                var item = data[i];
                                html += '<a class="page-search-item" data-id="' + item[settings.valueField] + '">' + item[settings.textField] + '</a>';
                            }
                            html += '</div>';
                            $(settings.tag).parent().css("position", "relative").append(html).find(".page-search").css("top", $(settings.tag).position().top + $(settings.tag).height() + 5).find(".page-search-item").click(function () {
                                for (var i = 0; i < data.length; i++) {
                                    var item = data[i];
                                    if ((item[settings.valueField] + "") == $(this).attr("data-id")) {
                                        settings.click(settings.tag, item);
                                        $(settings.tag).parent().find(".page-search").remove();
                                        $(settings.tag).val(item[settings.textField]);
                                        return;
                                    }
                                }
                            }).css("width", settings.width);
                        }
                    }
                });
            }
        }

        $(settings.tag).unbind("input");
        $(settings.tag).unbind("focus");
        $(settings.tag).unbind("blur");
        $(settings.tag).bind("input", load);
        $(settings.tag).bind("focus", load);
        $(settings.tag).bind("blur", function () {
            setTimeout(function () {
                $(settings.tag).parent().find(".page-search").remove();
            }, 500);
        });
    }
}
soon.service = function (settings) {

    if (settings == undefined) {
        settings = {
            url: "/",
            data: "",
            loading: false,
            error: function () {
                layer.open({
                    closeBtn: false,
                    title: "操作失败",
                    btn: ["重新连接"],
                    content: '互助助手连接失败，请检查互助助手是否正常运行',
                    yes: function (index) {
                        layer.close(index);
                        soon.service();
                    }
                })
            },
            success: function () { },
        };
    }

    settings = $.extend({
        url: "/",
        data: "",
        loading: false,
        error: function () { },
        success: function () { },
    }, settings || {});

    if (settings.loading != false) {
        settings.inx = layer.load(0);
    }

    $.ajax({
        url: 'http://127.0.0.1:41092' + settings.url,
        data: settings.data,
        type: "post",
        dataType: "json",
        cache: false,
        success: function (data) {
            if (settings.inx) {
                layer.close(settings.inx);
            }
            settings.success(data);
        },
        error: function () {
            $.ajax({
                url: 'http://127.0.0.1:26021' + settings.url,
                data: settings.data,
                async: false,
                type: "post",
                dataType: "json",
                cache: false,
                success: function (data) {
                    if (settings.inx) {
                        layer.close(settings.inx);
                    }
                    settings.success(data);
                },
                error: function () {
                    $.ajax({
                        url: 'http://127.0.0.1:38401' + settings.url,
                        data: settings.data,
                        async: false,
                        type: "post",
                        dataType: "json",
                        cache: false,
                        success: function (data) {
                            if (settings.inx) {
                                layer.close(settings.inx);
                            }
                            settings.success(data);
                        },
                        error: function () {
                            if (settings.inx) {
                                layer.close(settings.inx);
                            }
                            settings.error();
                        }
                    });
                }
            });
        }
    });

};
$.soon = soon;

if ($(".page-content").length > 0) {
    $(".page-content").css("min-height", $(window).height() - $(".page-header").height() - $(".page-footer").height() - 105);
}
$(".page-btn-signout").click(function () {
    layer.confirm('您确实要退出系统?', { icon: 3, title: '退出提示' }, function (index) {
        window.location.href = "/Unit/SignOut";
    });
});
$(".page-wrap-nav-item a").each(function () {

    if (window.location.href.indexOf($(this).attr("feature")) > -1) {
        $(this).addClass("on");
    }
});

$(".page-form-input-location").each(function () {

    var name = $(this).attr("name") ? $(this).attr("name") : "";
    var id = $(this).attr("id") ? $(this).attr("id") : ("i" + $.Guid());
    var parentid = $(this).attr("parentid") ? $(this).attr("parentid") : "0";
    var val = $(this).val() ? $(this).val() : "0";
    var load = function (pid, doc) {
        soon.ajax({
            url: "/Unit/Location?parentid=" + pid + "&val=" + val,
            dataType: "text",
            success: function (data) {
                if (data != "") {

                    doc.nextAll(".page-form-input-location-select").remove();
                    doc.prevAll(".page-form-input-location-select").removeAttr("name");
                    doc.removeAttr("name");

                    var did = ("i" + $.Guid());
                    var html = "<select id=" + did + " class='page-form-input-location-select' name='" + name + "' style=' margin-right:5px'>" + data + "</select>";
                    doc.after(html);
                    $("#" + did).change(function () {
                        load($("#" + did).val(), $("#" + did));
                    });
                    load($("#" + did).val(), $("#" + did));

                    if (pid == parentid) {
                        doc.remove();
                    }
                }
            }
        });
    }

    load(parentid, $(this));


});
$(".page-form-input-captcha").each(function () {
    var name = $(this).attr("name") ? $(this).attr("name") : "";
    var id = $(this).attr("id") ? $(this).attr("id") : ("i" + $.Guid());
    var doc = $(this);
    var load = function () {
        soon.ajax({
            url: "/Unit/Captcha",
            success: function (data) {
                doc.parent().find(".page-form-input-captcha-img").attr("src", data.img);
                doc.parent().find(".page-form-input-captcha-check").val(data.val);
            }
        });
    }
    doc.after('<img class="page-form-input-captcha-img" src=""/>');
    doc.after('<input class="page-form-input-captcha-check" type="hidden" name="' + name + '_Check" />');
    doc.parent().find(".page-form-input-captcha-img").click(function () {
        load();
    });
    load();
});

$(".page-form-input-img").each(function () {
    var html = "<div class='page-form-input-img-box'>";
    html += '<img src="/unit/resource/img/add.png" />';
    html += '<input type="file" accept=".jpg,.jpge,.gif,.png" />';
    html += "</div>";
    $(this).append(html);
    var inputVal = $(this).find("input[type=hidden]");
    var img = $(this).find("img");
    $(this).find("input[type=file]").change(function (e) {
        var filemaxsize = 1024;
        var size = e.target.files[0].size / 2048;
        if (size > filemaxsize) {
            layer.msg("图片不能超过2M，请重新选择!");
        }
        else if (!e.target.files[0].type.match(/image.*/)) {
            layer.msg('请选择正确的图片!');
        } else {

            var reader = new FileReader();
            reader.onload = function (evt) {
                inputVal.val(evt.target.result.replace("data:image/jpeg;base64,", "").replace("data:image/jpg;base64,", "").replace("data:image/png;base64,", "").replace("data:image/gif;base64,", ""));
                img.attr("src", evt.target.result);
                e.target.value = "";
            }
            reader.readAsDataURL(e.target.files[0]);

        }
    });
});
$(".page-tab-event span").click(function () {
    $(this).parent().find("span").removeClass("on");
    $(this).addClass("on");
    $(this).parent().parent().find(".page-tab-content").hide().eq($(this).index()).show();
});
$(".page-tab-event").each(function () {
    $(this).find("span").eq(0).click();
});
$(".page-form-input-number").each(function () {

    if (window._form_input_parameter == undefined) {
        window._form_input_parameter = [];
    }

    var min = $(this).attr("data-min") ? parseInt($(this).attr("data-min")) : 0;
    var max = $(this).attr("data-max") ? parseInt($(this).attr("data-max")) : 0;
    var name = $(this).attr("data-name") ? $(this).attr("data-name") : "";
    var id = $(this).attr("id") ? $(this).attr("id") : ("i" + $.Guid());
    $(this).attr("id", id);
    var callback = {
        id: id,
        fn: function () { }
    };
    var val = $(this).html() == "" ? min : parseInt($(this).html());
    $(this).html("<a><i class='fa fa-plus'></i></a><input name='" + name + "' value='" + val + "' /><a><i class='fa fa-minus'></i></a>");
    var valInput = $(this).find("input");
    $(this).find("a").eq(0).click(function () {
        if (val + 1 <= max) {
            val++;
            valInput.val(val);
            callback.fn(val);
        }
    });
    $(this).find("a").eq(1).click(function () {
        if (val - 1 >= min) {
            val--;
            valInput.val(val);
            callback.fn(val);
        }
    });
    $(this).bind("selectstart", function () { return false; });
    $(this).bind("copy", function () { return false; });
    window._form_input_parameter.push(callback);
});
$(".page-form-date").each(function () {
    layui.laydate.render({
        elem: this
    });
});


$.fn.extend({
    inputnumber: function (fn) {
        if (fn && window._form_input_parameter != undefined) {
            var id = $(this).attr("id");
            for (var i = 0; i < window._form_input_parameter.length; i++) {
                var item = window._form_input_parameter[i];
                if (item.id == id) {
                    item.fn = fn;
                    break;
                }
            }
        }
    }
});